package com.bestcem.xm.om.util;

import com.bestcem.xm.om.controller.param.EmailParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Objects;
import java.util.Properties;

/**
 * @author zq.ding <zq.ding@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/18 11:09
 */
@Slf4j
public class EmailUtil {
    private EmailUtil() {
    }

    /**
     * 根据邮箱账号的相关信息校验邮箱真实性
     *
     * @param param 邮件验证参数
     * @return 是否验证通过
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/11/18 11:09
     */
    public static boolean validateMail(@NotNull EmailParam param) {
        // 1.尝试连接,测试参数中的host和port是否正确
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(param.getHost(), param.getPort()), 1000);
        } catch (IOException e) {
            if (log.isInfoEnabled()) {
                log.info("[OM] 邮箱域名:{},端口:{} 无效 ;", param.getHost(), param.getPort());
            }
            return false;
        }
        // 2.设置javaMailSender
        JavaMailSenderImpl javaMailSender = getJavaMailSenderByMailParam(param);
        return sendMail(javaMailSender, new String[]{param.getAccount()}, "通知中心邮箱添加", "<h1>您的邮箱正在被添加到--通知中心--发件人列表中,如果这不是您本人的意愿,请立即更换密码</h1>");
    }

    /**
     * 根据param获取JavaMailSenderImpl
     *
     * @param param 创建对象的入参
     * @return 新创建的JavaMailSenderImpl
     */
    public static JavaMailSenderImpl getJavaMailSenderByMailParam(@NotNull EmailParam param) {
        // 2.设置javaMailSender
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setProtocol("smtp");
        javaMailSender.setHost(param.getHost().trim());
        javaMailSender.setUsername(param.getAccount());
        javaMailSender.setPassword(param.getPassword());
        javaMailSender.setDefaultEncoding("UTF-8");
        Properties properties = new Properties();
        // 设置超时时间
        properties.setProperty("mail.smtp.timeout", "5000");
        // 如果是ssl的话,需要设置以下属性
        if (Boolean.TRUE.equals(param.getSsl())) {
            // debug时使用
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(param.getPort()));
        }
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }

    /**
     * 发送邮件
     *
     * @param javaMailSender 灵活的创建javaMailSender
     * @param to             收件人
     * @param subject        主题
     * @param context        内容
     * @return 是否发送成功
     */
    public static boolean sendMail(@NotNull JavaMailSenderImpl javaMailSender, @NotNull String[] to, String subject, @NotNull String context) {
        return sendMail(javaMailSender, javaMailSender.getUsername(), to, subject, context);
    }

    public static boolean sendMail(@NotNull JavaMailSenderImpl javaMailSender, String from, @NotNull String[] to, String subject, @NotNull String context) {
        if (log.isInfoEnabled()) {
            log.info("[OM] 开始发送邮件,变量:{} ", javaMailSender.toString());
        }

        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(context, true);
            javaMailSender.send(message);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.error("[OM] 发送邮件至{}异常,发件者: {} ;{}", to, javaMailSender.getUsername(), e.getMessage());
            }
            return false;
        }

        if (log.isInfoEnabled()) {
            log.info("[OM] 邮件已发送至{},发件者: {} ;", to, javaMailSender.getUsername());
        }
        return true;
    }
    public static boolean sendMail(@NotNull JavaMailSenderImpl javaMailSender, String from, @NotNull String[] to, String[] cc, String subject, @NotNull String context) {
        if (log.isInfoEnabled()) {
            log.info("[OM] 开始发送邮件,变量:{} ", javaMailSender.toString());
        }

        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            if (Objects.nonNull(cc) && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            helper.setText(context, true);
            javaMailSender.send(message);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.error("[OM] 发送邮件至{}异常,发件者: {} ;{}", to, javaMailSender.getUsername(), e.getMessage());
            }
            return false;
        }

        if (log.isInfoEnabled()) {
            log.info("[OM] 邮件已发送至{},发件者: {} ;", to, javaMailSender.getUsername());
        }
        return true;
    }
}
